package com.zidongxiangxi.clock.server.business;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zidongxiangxi.clock.server.repository.entity.Clock;
import com.zidongxiangxi.clock.server.task.ClockTimerTask;
import io.netty.util.HashedWheelTimer;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenxudong
 * @date 2021/06/07
 */
@Component
@Slf4j
public class ClockTaskBusiness {

    @Autowired
    @Qualifier("asyncExecutor")
    private ThreadPoolExecutor executor;

    @Autowired
    private ClockBusiness clockBusiness;

    private static final HashedWheelTimer MILLI_SECOND_TIMER =
        new HashedWheelTimer(new NamedThreadFactory("clock-wheel-timer"), 100, TimeUnit.MILLISECONDS);

    public void addClockTask(List<Clock> alarmClocks) {
        if (CollectionUtils.isEmpty(alarmClocks)) {
            return;
        }
        alarmClocks.forEach(this::addClockTask);
    }

    public void addClockTask(Clock alarmClock) {
        if (Objects.isNull(alarmClock)) {
            return;
        }
        long delayTime = alarmClock.getNextTryTime() - System.currentTimeMillis();
        MILLI_SECOND_TIMER.newTimeout(newClockTimerTask(alarmClock), delayTime, TimeUnit.MILLISECONDS);
    }

    private TimerTask newClockTimerTask(Clock alarmClock) {
        return new ClockTimerTask(executor, clockBusiness, alarmClock);
    }

}
